<?php

/**
 * Notes:
 * You maybe tempted to create unlink method for delete purpose and attach this
 * behavior to ActiveRecord, but that's a foolish refactoring. Let's make this
 * behavior only react to CUploadedFile only.
 */
class EUploadedFileBehavior extends CBehavior {

	protected function resampleImage($width = false, $height = false,
		$lockRatio = true) {
		if (!$image = $this->createImageFromFile())
			return null;
		if (!$info = getimagesize($this->owner->tempName))
			return null;
		if ($lockRatio) {
			$ratio = $info[0] / $info[1];
			if ($width && $height) {
				if ($width / $height > $ratio)
					$width = $height * $ratio;
				else
					$height = $width / $ratio;
			} elseif ($width) {
				$height = $width / $ratio;
			} else {
				$width = $height * $ratio;
			}
		}
		if (!$width)
			$width = $info[0];
		if (!$height)
			$height = $info[1];
		$resampled = imagecreatetruecolor($width, $height);
		imagecopyresampled(
			$resampled, $image, 0, 0, 0, 0, $width, $height, $info[0], $info[1]
		);
		return $resampled;
	}

	private function createImageFromFile() {
		$filename = $this->owner->tempName;
		if (!$info = getimagesize($filename))
			return false;
		$type = $info[2];
		if ($type == 1): // GIF
			return @imagecreatefromgif($filename);
		elseif ($type == 2): // JPG
			return @imagecreatefromjpeg($filename);
		elseif ($type == 3): // PNG
			return @imagecreatefrompng($filename);
		elseif ($type == 4): // SWF
			return false;
		elseif ($type == 5): // PSD
			return false;
		elseif ($type == 6): // BMP
			return false;
		elseif ($type == 7): // TIFF(intel byte order)
			return false;
		elseif ($type == 8): // TIFF(motorola byte order)
			return false;
		elseif ($type == 9): // JPC
			return false;
		elseif ($type == 10): // JP2
			return false;
		elseif ($type == 11): // JPX
			return false;
		elseif ($type == 12): // JB2
			return false;
		elseif ($type == 13): // SWC
			return false;
		elseif ($type == 14): // IFF
			return false;
		elseif ($type == 15): // WBMP
			return @imagecreatefromwbmp($filename);
		elseif ($type == 16): // XBM
			return @imagecreatefromxbm($filename);
		else:
			return false;
		endif;
	}

	protected function saveAsPng($path, $width = false, $height = false,
		$lockRatio = true
	) {
		$resampled = $this->resampleImage($width, $height, $lockRatio);
		return imagepng($resampled, $path);
	}

	protected function saveAsJpeg($path, $width = false, $height = false,
		$lockRatio = true, $quality = 75
	) {
		$resampled = $this->resampleImage($width, $height, $lockRatio);
		return imagejpeg($resampled, $path, $quality);
	}
	
}
